/**
 * 
 */
package myth.cc.loc;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

import myth.cc.file.SourceFileReader;

/**
 * @author Biao Zhang
 *
 */
public class JavaLocCounter implements LocCount {
	private SourceFileReader fileReader = null;
	private BufferedReader bufferedReader = null;
	private String current = null;
	private int loc = 0;
	
	private int state = 0;
	private static final int IN_COMMENT = 0;
	private static final int OUT_COMMENT = 1;
	
	public JavaLocCounter(String fileName) {
		loc = 0;
		state = OUT_COMMENT;
		
		fileReader = new SourceFileReader(fileName);
		try {
			bufferedReader = new BufferedReader(new StringReader(fileReader.getSource()));
			current =  _getNext();
			loc++;
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
		
		
	}
	
	/* (non-Javadoc)
	 * @see myth.cc.loc.LocCount#getCurrentLineNum()
	 */
	public int getCurrentLineNum() {
		return loc;
	}

	/* (non-Javadoc)
	 * @see myth.cc.loc.LocCount#getLines()
	 */
	public String[] getLines() {
		// TODO Auto-generated method stub
		return null;
	}

	
	/**
	 * 
	 */
	private String _getNext() {
		String temp = null;
		try {
			temp = bufferedReader.readLine();
			
			switch(state) {
			case IN_COMMENT:
				if (temp.endsWith("*/")) {
					state = OUT_COMMENT;
				}
				break;
			case OUT_COMMENT:
				if (temp.startsWith("/*")) {
					state = IN_COMMENT;
				} else if (temp.startsWith("//")) {
					
				} else {
					loc++;
				}
				break;
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
		return temp;
	}

	/* (non-Javadoc)
	 * @see myth.cc.loc.LocCount#hasNext()
	 */
	public boolean hasNext() {
		return current == null;
	}

	/* (non-Javadoc)
	 * @see myth.cc.loc.LocCount#reverse()
	 */
	public void reset() {
		try {
			bufferedReader.reset();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
		
		loc = 0;
		state = OUT_COMMENT;
	}

	/* (non-Javadoc)
	 * @see myth.cc.loc.LocCount#getNext()
	 */
	public String getNext() {
		String temp = current;
		current = _getNext();
		return temp;
	}

}
